package com.le.edu.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.le.edu.domain.entity.UploadResult;
import com.le.edu.exception.AppException;
import com.le.edu.properties.OssProperties;
import com.le.edu.service.OssService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author Le
 * @create 2024-04-09 17:20
 */
@Service
@RequiredArgsConstructor
public class OssServiceImpl implements OssService {
    private final OssProperties properties;
    private final AmazonS3 amazonS3;


    @Override
    public UploadResult uploadFile(MultipartFile file) {
        String filePath;
        String originalFilename = file.getOriginalFilename();
        try {
            InputStream is = file.getInputStream();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(is.available());

            String fileName = IdUtil.simpleUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            filePath = DateUtil.today().replaceAll("-", "/") + "/" + fileName;

            PutObjectRequest putObjectRequest = new PutObjectRequest(properties.getBucketName(), filePath, is, metadata);
            // 设置上传对象的 Acl 为公共读
            putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
            amazonS3.putObject(putObjectRequest);
        } catch (Exception e) {
            throw new AppException("上传文件失败，请检查配置信息:[" + e.getMessage() + "]");
        }
        return UploadResult.builder().url(getPathUrl(filePath)).filename(originalFilename).build();
    }

    private String getPathUrl(String filePath) {
        return StrUtil.format("{}/{}/{}", properties.getEndpoint(), properties.getBucketName(), filePath);
    }
}
